<!DOCTYPE html>
<html lang="zh-cn">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .done {
            color: gray;
            text-decoration: line-through;
        }
    </style>
</head>

<body>
    <h1>TODO List</h1>
    <div id="app">
        <input type="text" v-model="title" @keydown.enter="addTodo">
        <ul v-if="todos.length">
            <li v-for="todo in todos">
                <input type="checkbox" v-model="todo.done">
                <span :class="{done:todo.done}">{{ todo.title }}</span>
            </li>
        </ul>
        <div v-else>
            输入待办事项后按 enter 以添加。
        </div>
        <div>
            <p>{{active}} / {{all}}</p>
            <p> 全部完成 <input type="checkbox" v-model="allDone"> </p>
            <button v-if="active<all" @click="clear">清除完成项</button>
        </div>
    </div>
    
    <script src="https://unpkg.com/vue@next"></script>
    <script>
        const App = {
            data() {
                return {
                    title: "",
                    todos: []
                }
            },
            mounted() {
                cache = localStorage.getItem("todos");
                console.log(cache);
                if (cache != "undefined"){
                    this.todos = JSON.parse(cache)
                }
            },
            methods: {
                addTodo() {
                    this.todos.push(
                        { title: this.title, done: false }
                    )
                    this.title = ""
                },
                clear() {
                    this.todos = this.todos.filter(v=>!v.done)
                }
            },
            computed:{
                active(){
                    return this.todos.filter(v=>!v.done).length
                },
                all(){
                    return this.todos.length
                },
                allDone: {
                    get: function() {
                        return this.active === 0
                    },
                    set: function (val) {
                        this.todos.forEach(todo=>{
                            todo.done = val
                        });
                    }
                }
            },
            watch: {
                todos: {
                    handler(newTodos, oldTodos) {
                        console.info("todos changed")
                        localStorage.setItem("todos", JSON.stringify(this.todos))
                    },
                    deep: true
                }
            }
        }

        Vue.createApp(App).mount("#app")
    </script>

</body>

</html>